package beanstao.util.socket;

import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketAddress;

import beanstao.util.log.ILog;
import beanstao.util.log.LogHelper;

/**
 * 一个实现了线程化的SocketClient,较简单。<BR>
 * TODO：应该考虑使用线程池
 * 
 * @author beanstao@google.com 
 */
public class SocketClient extends Thread implements ILog
{
	private Socket client = null;
	private final String ipAddress;
	private final int port;

	public static SocketClient ME(String ipAddress, int port)
	{
		return new SocketClient(ipAddress, port);
	}

	protected SocketClient(String ipAddress, int port)
	{
		this.ipAddress = ipAddress;
		this.port = port;
	}

	/**
	 * 核心方法，向服务器端写入数据
	 * 
	 * @param msg
	 * @return
	 */
	public boolean write(String msg)
	{
		try
		{
			SocketAddress address = new InetSocketAddress(this.ipAddress, this.port);
			this.client = new Socket();
			this.client.connect(address, 600);
		}
		catch (Exception e)
		{
			this.logWarn("连接服务器获取SOCKET。异常。", e);
		}
		OutputStream outputStream = null;
		try
		{
			outputStream = this.client.getOutputStream();
		}
		catch (Exception e)
		{
			this.logWarn("从服务器获取SOCKET流异常。", e);
		}
		BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(outputStream));
		try
		{
			bw.write(msg);
			bw.flush();
		}
		catch (IOException e)
		{
			this.logWarn("向SOCKET流写入数据时异常。", e);
		}
		try
		{
			bw.close();
		}
		catch (IOException e)
		{
			this.logWarn("关闭SOCKET流异常。", e);
			return false;
		}
		try
		{
			this.client.close();
		}
		catch (IOException e)
		{
			this.logWarn("关闭SOCKET CLIENT异常。", e);
			return false;
		}
		this.logDebug("向服务器发送消息正常，Client已关闭。MSG：" + msg);
		return true;
	}

	@Override
	public void run()
	{
		this.logDebug("启动一个SOCKET CLIENT线程。");
	}

	// = 日志接口(ILog)的实现 ============

	@Override
	public void logDebug(final Object message)
	{
		LogHelper.logDebug(this, message);
	}

	@Override
	public void logDebug(final Object message, final Throwable t)
	{
		LogHelper.logDebug(this, message, t);
	}

	@Override
	public void logError(final Object message)
	{
		LogHelper.logError(this, message);
	}

	@Override
	public void logError(final Object message, final Throwable t)
	{
		LogHelper.logError(this, message, t);
	}

	@Override
	public void logInfo(final Object message)
	{
		LogHelper.logInfo(this, message);
	}

	@Override
	public void logInfo(final Object message, final Throwable t)
	{
		LogHelper.logInfo(this, message, t);
	}

	@Override
	public void logWarn(final Object message)
	{
		LogHelper.logWarn(this, message);
	}

	@Override
	public void logWarn(final Object message, final Throwable t)
	{
		LogHelper.logWarn(this, message, t);
	}

}
